/*
 * Copyright (c) 2018.
 * http://www.ulabcare.com
 */

package com.mt.roll.core.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * 获取bean的工具类，可用于在线程里面获取bean
 *
 * @author jiff
 * @date 2018-11-30
 * @since 1.0
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context = null;


    /**
     * @param applicationContext
     * @throws BeansException
     * @see ApplicationContextAware#setApplicationContext(ApplicationContext)
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }


    /**
     * @param name bean名称
     * @param <T>  返回bean的类型
     * @return bean
     */
    public static <T> T getBean(String name) {
        return (T) context.getBean(name);
    }

    /**
     * @param name         bean名称
     * @param requiredType bean类型
     * @param <T>          bean类型
     * @return bean
     */
    public static <T> T getBean(String name, @Nullable Class<T> requiredType) {
        return context.getBean(name, requiredType);
    }

    /**
     * @param requiredType bean类型
     * @param <T>          bean类型
     * @return bean
     */
    public static <T> T getBean(Class<T> requiredType) {
        return context.getBean(requiredType);
    }

    /**
     * 国际化消息
     *
     * @param key  消息键值
     * @param args 消息需要的参数
     * @return 消息
     */
    public static String getMessage(String key, @Nullable Object[] args) {
        return context.getMessage(key, args, Locale.getDefault());
    }

    /**
     * 获取当前环境
     *
     * @return 当前环境：dev、test、pro
     */
    public static String getActiveProfile() {
        return context.getEnvironment().getActiveProfiles()[0];
    }
}
